package com.jwsoft.manager.core.integration.impl;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.servlet.ServletUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.bifang.assistant.common.vo.OrderVO;
import com.bifang.assistant.common.vo.SessionInfo;
import com.bifang.engine.assistant.core.annotation.ApiService;
import com.bifang.engine.assistant.core.annotation.OpApi;
import com.bifang.engine.assistant.core.annotation.SaveOplog;
import com.bifang.engine.assistant.core.enums.AuTypeEnum;
import com.bifang.engine.assistant.core.enums.AuthStatusEnum;
import com.bifang.engine.assistant.core.enums.BoolEnum;
import com.bifang.engine.assistant.core.enums.FuncTypeEnum;
import com.bifang.engine.assistant.core.exception.AppException;
import com.bifang.engine.assistant.core.utils.SessionUtil;
import com.bifang.engine.cache.redis.RedisHelper;
import com.bifang.engine.data.core.util.PagerUtil;
import com.bifang.module.base.common.util.ApplicationContextHelper;
import com.bifang.module.base.common.vo.dict.DictAreaVO;
import com.bifang.module.base.common.vo.dict.SelectVO;
import com.bifang.module.base.common.vo.excel.ExcelModelVO;
import com.bifang.module.base.common.vo.excel.ExcelVO;
import com.bifang.module.base.core.helper.ApiContainer;
import com.bifang.module.base.core.helper.ApiModel;
import com.bifang.module.base.core.helper.DictHelper;
import com.bifang.module.base.core.helper.ExcelCommonHelper;
import com.bifang.module.base.core.integration.DictIntegration;
import com.bifang.module.base.core.integration.ExcelIntegration;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.jwsoft.manager.common.constant.EduCache;
import com.jwsoft.manager.common.enums.*;
import com.jwsoft.manager.common.vo.YwApply.CompanyVO;
import com.jwsoft.manager.common.vo.YwApply.EnrollCheckShLqVO;
import com.jwsoft.manager.common.vo.YwApply.LivePlaceVO;
import com.jwsoft.manager.common.vo.YwApply.StudentStatusVO;
import com.jwsoft.manager.common.vo.cache.EduOperationCacheDetailVO;
import com.jwsoft.manager.common.vo.cache.EduOperationCacheQueryVO;
import com.jwsoft.manager.common.vo.cache.EduOperationCacheVO;
import com.jwsoft.manager.common.vo.eduFormEnrollParams.EduFormEnrollParamsVO;
import com.jwsoft.manager.common.vo.eduHouse.EduHouseVO;
import com.jwsoft.manager.common.vo.eduHousehold.EduHouseholdVO;
import com.jwsoft.manager.common.vo.eduNetsign.EduNetsignVO;
import com.jwsoft.manager.common.vo.eduSchool.EduSchoolVO;
import com.jwsoft.manager.common.vo.eduSocialSecurity.EduSocialSecurityVO;
import com.jwsoft.manager.common.vo.eduStudentEnroll.*;
import com.jwsoft.manager.common.vo.eduStudentEnrollReview.EduStudentEnrollReviewVO;
import com.jwsoft.manager.common.vo.eduStudentEnrollVerification.EduMateria;
import com.jwsoft.manager.common.vo.eduStudentEnrollVerification.EduStudentEnrollVerificationVO;
import com.jwsoft.manager.common.vo.eduSystemConfig.EduSystemConfigFuncQueryVO;
import com.jwsoft.manager.core.dao.model.*;
import com.jwsoft.manager.core.dao.service.*;
import com.jwsoft.manager.core.integration.EduStudentEnrollImitateIntegration;
import com.jwsoft.manager.core.integration.EduSystemConfigIntegration;
import com.jwsoft.manager.core.integration.OperationCacheIntegration;
import com.jwsoft.manager.core.util.EduDesensitizeUtil;
import com.jwsoft.manager.core.util.EduEnrollClearCacheHelper;
import com.jwsoft.manager.core.util.EduHelper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 模拟报名业务实现类
 *
 * @author chenzh
 * @since 2024-03-11
 */
@ApiService(funcCode = "enrollImitate", title = "模拟报名")
public class EduStudentEnrollImitateIntegrationImpl implements EduStudentEnrollImitateIntegration {
    @Autowired
    private RedisHelper redisHelper;
    @Autowired
    public EduStudentEnrollImitateService eduStudentEnrollService;
    @Autowired
    private EduSystemConfigIntegration eduSystemConfigIntegration;
    @Autowired
    private EduStudentEnrollVerificationService eduStudentEnrollVerificationService;
    @Autowired
    EduHelper eduHelper;
    @Autowired
    private DictIntegration dictIntegration;
    @Autowired
    private DictHelper dictHelper;
    @Autowired
    private EduAreaService eduAreaService;
    @Autowired
    private EduSchoolService eduSchoolService;
    @Autowired
    private EduStudentEnrollInvalidService eduStudentEnrollInvalidService;
    @Autowired
    private EduEnrollClearCacheHelper eduEnrollClearCacheHelper;
    @Autowired
    private EduStudentEnrollPreService eduStudentEnrollPreService;
    @Autowired
    private OperationCacheIntegration operationCacheIntegration;
    @Autowired
    private ApiContainer apiContainer;
    @Autowired
    private EduFormSpecialParamsService eduFormSpecialParamsService;
    @Autowired
    private EduFormEnrollParamsService eduFormEnrollParamsService;
    @Autowired
    private EduNetsignService eduNetsignService;
    @Autowired
    private EduSocialSecurityService eduSocialSecurityService;
    @Autowired
    private EduCompanyService eduCompanyService;
    @Autowired
    private EduStudentStatusService eduStudentStatusService;
    @Autowired
    private EduHouseService eduHouseService;
    @Autowired
    private EduhHouseService eduhHouseService;
    @Autowired
    private EduHouseholdService eduHouseholdService;
    @Autowired
    private EduLivePlaceService eduLivePlaceService;
    @Autowired
    private EduSchoolConfigService eduSchoolConfigService;
    @Autowired
    private EduEnrollmenBrochureService eduEnrollmenBrochureService;
    @Autowired
    private EduStudentEnrollReviewService eduStudentEnrollReviewService;
    @Autowired
    private ExcelCommonHelper excelCommonHelper;
    @Autowired
    private ExcelIntegration excelIntegration;
    @Value("${spring.servlet.multipart.location}")
    private String tempPath;
    @Override
    @OpApi(funcCode = "enrollImitate0001", title = "模拟报名分页查询", funcType = FuncTypeEnum.query)
    public PageInfo<EduStudentEnrollVO> getList(EduStudentEnrollQueryVO vo) {
        if (!vo.getIsGly()) {//不是赋给管理员查询就获取当前用户组织ID查询
            vo.setSchoolId(SessionUtil.getSessionInfo().getOrgId());
        }
        if (vo.getPageNum() == null || vo.getPageSize() == null) {
            //如果不传入分页参数，默认最大取1000条
            vo.setPageNum(1);
            vo.setPageSize(20);
        }
        if (ObjectUtils.isEmpty(vo.getYear())) {
            vo.setYear(eduHelper.thisYear());
        }
        if (StringUtils.isBlank(vo.getOpType())) {
            vo.setOpType("9");
        }
        EnrollCheckShLqVO checkShLqVO = new EnrollCheckShLqVO();
        checkShLqVO.setYear(vo.getYear());
        checkShLqVO.setOpType(vo.getOpType());
        checkShLqVO.setSchoolId(vo.getSchoolId());
        checkShLqVO.setAreaCode(vo.getAreaCode());
        Boolean checkFlag = checkShLq(checkShLqVO);
        if (!checkFlag) {
            throw new AppException("本年度模拟报名审核工作尚未开始");
        }
        if (!CollectionUtils.isEmpty(vo.getOrderVOList())) {
            String orderBy = "";
            for (OrderVO orderVO : vo.getOrderVOList()) {
                if (StringUtils.isNotBlank(orderVO.getOrder()) && StringUtils.isNotBlank(orderVO.getProperty())) {
                    orderBy = orderBy + ",";
                    if (orderVO.getProperty().equals("registerDate")) {
                        orderBy = orderBy + "a.";
                    } else if (orderVO.getProperty().equals("qysj")) {
                        orderBy = orderBy + "a.";
                    } else {
                        orderBy = orderBy + "a.";
                    }
                    orderBy = orderBy + StrUtil.toUnderlineCase(orderVO.getProperty()) + " " + orderVO.getOrder();
                }
            }
            vo.setOrderBy(orderBy);

        }

        List<String> areaCodeList = new ArrayList<>();
        if (ObjectUtils.isEmpty(vo.getAreaCode())) {
            List<SelectVO> selectVOList = dictIntegration.getDistrictByOrg(new DictAreaVO());
            areaCodeList = selectVOList.stream()
                    .map(SelectVO::getDictKey)
                    .collect(Collectors.toList());
            String sessionAreaCode = SessionUtil.getAreaCode();
            if (!areaCodeList.contains(sessionAreaCode)) {
                areaCodeList.add(sessionAreaCode);
            }
        } else {
            areaCodeList.add(vo.getAreaCode());
        }
        if (!CollectionUtils.isEmpty(areaCodeList)) {
            vo.setAreaCodeList(areaCodeList);
        } else {
            throw new AppException("必须传入行政区划");
        }
        PageHelper.startPage(vo.getPageNum(), vo.getPageSize());
        List<EduStudentEnrollVO> list = eduStudentEnrollService.getYwApplyList(vo);


        if (CollectionUtils.isEmpty(list)) {
            // 判断是否为空，为空则返回空参数
            return PagerUtil.createEmptyPagerInfo(vo.getPageNum(), vo.getPageSize());
        }
        for (EduStudentEnrollVO enrollVO : list) {
            /*
             * source:6 学校录入报名数据
             * */
            if (StringUtils.isNotEmpty(enrollVO.getSource())) {
                if ("6".equals(enrollVO.getSource())) {
                    enrollVO.setFileInfo(enrollVO.getParam20());
                }
            }
        }
        // 不为空则获取分页结果
        PageInfo<EduStudentEnrollVO> pageInfo = new PageInfo<>(list);
        // 返回参数需要通过common层的vo实体类，用该方法可以批量转换
        List<EduStudentEnrollVO> resultList = pageInfo.getList();
        dictHelper.valueToName(resultList, Arrays.asList(EduYwEnrollDictEnum.values()));
        Map<String, EduArea> areaMap =
                eduAreaService.list().stream()
                        .collect(Collectors.toMap(EduArea::getAreaCode, a -> a, (k1, k2) -> k1));
        boolean flag = false;
        String cqSchool = "all";//commonIntegration.getValueByKey("cq_school");
        Map<String, EduStudentEnrollImitate> map = new HashMap<>();

        //获取报名id
        List<String> enrollIdList = resultList.stream().map(EduStudentEnrollVO::getStudentEnrollId).distinct().collect(Collectors.toList());
        List<String> authStatusList = new ArrayList<>();
        authStatusList.add(AuthStatusEnum.NODO.getType());
        authStatusList.add(AuthStatusEnum.YES.getType());
        QueryWrapper<EduStudentEnrollInvalid> invalidQueryWrapper = new QueryWrapper<>();
        invalidQueryWrapper.lambda()
                .select(EduStudentEnrollInvalid::getStudentEnrollId, EduStudentEnrollInvalid::getAuthStatus)
                .in(EduStudentEnrollInvalid::getStudentEnrollId, enrollIdList)
                .in(EduStudentEnrollInvalid::getAuthStatus, authStatusList);
        List<EduStudentEnrollInvalid> invalidList = eduStudentEnrollInvalidService.list(invalidQueryWrapper);
        Map<String, String> collectMap = new HashMap<>();
        if (!CollectionUtils.isEmpty(invalidList)) {
            collectMap = invalidList.stream().collect(Collectors.toMap(EduStudentEnrollInvalid::getStudentEnrollId, EduStudentEnrollInvalid::getAuthStatus));
        }


        for (EduStudentEnrollVO studentEnroll : resultList) {
            studentEnroll.setDelStatus(collectMap.get(studentEnroll.getStudentEnrollId()));

            if (!flag && EnrollStatusFormalEnum.dlq.getType().equals(studentEnroll.getEnrollStatus())) {
                flag = true;
                studentEnroll.setFirstFlag(true);
            } else {
                studentEnroll.setFirstFlag(false);
            }
            //设置街道
            if (!ObjectUtils.isEmpty(areaMap.get(studentEnroll.getStreet()))) {
                studentEnroll.setStreetName(areaMap.get(studentEnroll.getStreet()).getAreaName());
            }
            if (StringUtils.isBlank(studentEnroll.getAdmitFlag())) {
                studentEnroll.setAdmitFlag("2");
                studentEnroll.setAdmitFlagName("待录取");
            } else {
                if (BoolEnum.TRUE.getType().equals(studentEnroll.getAdmitFlag())) {
                    studentEnroll.setAdmitFlagName("已录取");
                } else {
                    studentEnroll.setAdmitFlagName("不予录取");
                }
            }
            if (BoolEnum.TRUE.getType().equals(studentEnroll.getSpecialFlag())) {
                studentEnroll.setSpecialFlagName("是");
            } else {
                studentEnroll.setSpecialFlagName("否");
            }
            if (StringUtils.isNotBlank(studentEnroll.getEnrollStatus())) {
                EnrollStatusFormalEnum formalEnum = EnrollStatusFormalEnum.getByType(studentEnroll.getEnrollStatus());
                studentEnroll.setEnrollStatusName(formalEnum == null ? "未知状态" : formalEnum.getName());
            } else {
                studentEnroll.setEnrollStatus(EnrollStatusFormalEnum.dsh.getType());
                studentEnroll.setEnrollStatusName(EnrollStatusFormalEnum.dsh.getName());
            }
        }

        return PagerUtil.parsePagerVo(resultList, pageInfo);
    }


    @Override
    @OpApi(funcCode = "enrollImitate0002", title = "模拟报名根据主键查询详情", funcType = FuncTypeEnum.query)
    public EduStudentEnrollVO getById(EduStudentEnrollKeyVO vo) {
        EduStudentEnrollImitate entity = eduStudentEnrollService.getById(vo.getStudentEnrollId());
        if (ObjectUtils.isEmpty(entity)) {
            throw new AppException("查询不到详细信息!");
        }
        EduStudentEnrollVO result = Convert.convert(EduStudentEnrollVO.class, entity);
        QueryWrapper<EduStudentEnrollVerification> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(EduStudentEnrollVerification::getStudentEnrollId, result.getStudentEnrollId());
        List<EduStudentEnrollVerification> list = eduStudentEnrollVerificationService.list(queryWrapper);
        if (!CollectionUtils.isEmpty(list)) {
            result.setVerificationVOList(Convert.toList(EduStudentEnrollVerificationVO.class, list));
        }
        return result;
    }

    /**
     * 保存前统一校验
     */
    @Override
    @OpApi(funcCode = "enrollImitate0003", title = "模拟报名保存前校验", funcType = FuncTypeEnum.other, checkPrivilege = BoolEnum.FALSE)
    public void checkSave(SaveStudentEnrollVO vo) {
        //主键为空为新增校验

        //主键不为空为修改校验
    }

    @Override
    @OpApi(funcCode = "enrollImitate0004", title = "模拟报名新增-线下录入", funcType = FuncTypeEnum.insert)
    @SaveOplog(
            operationType = "enrollImitate0004",
            operationName = "模拟报名新增-线下录入",
            dataType = "studentEnrollId",
            auType = AuTypeEnum.OTHER)
    @Transactional
    public SaveStudentEnrollVO add(SaveStudentEnrollVO vo) {
        vo.setLrFlag(true);
        return saveEnroll(vo);
    }

    @Override
    @OpApi(funcCode = "enrollImitate0019", title = "app端家长模拟报名保存", funcType = FuncTypeEnum.insert)
    @SaveOplog(
            operationType = "enrollImitate0019",
            operationName = "app端家长模拟报名保存",
            dataType = "studentEnrollId",
            auType = AuTypeEnum.OTHER)
    @Transactional
    public SaveStudentEnrollVO saveEnrollApp(SaveStudentEnrollVO vo) {
        vo.setLrFlag(false);
        return saveEnroll(vo);
    }

    //动态调用报名个性化方法
    private SaveStudentEnrollVO saveEnroll(SaveStudentEnrollVO vo) {
        EduSchoolVO schoolVO = eduSchoolService.getDetail(vo.getSchoolId());
        if (schoolVO == null) {
            throw new AppException("报名的学校不存在");
        }
        EduSystemConfigFuncQueryVO queryVO = new EduSystemConfigFuncQueryVO();
        queryVO.setAccessToken(vo.getAccessToken());
        queryVO.setAreaCode(schoolVO.getAreaCode());
        queryVO.setEduConfigKey("saveImitateEnroll");
        String funcCode = eduSystemConfigIntegration.getFuncCode(queryVO);
        ApiModel apiModel = apiContainer.get(funcCode);
        if (apiModel != null) {
            try {
                Object bean = ApplicationContextHelper.getBean(apiModel.getBeanName());
                if (null != bean) {
                    apiModel.getMethod().invoke(bean, vo);
                    eduEnrollClearCacheHelper.clearCacheMyEnroll(vo.getIdcard());
                    eduEnrollClearCacheHelper.clearCacheMyEnroll(vo.getFatherIdcard());
                    eduEnrollClearCacheHelper.clearCacheMyEnroll(vo.getMotherIdcard());
                    eduEnrollClearCacheHelper.clearCacheMyEnrollPre(vo.getIdcard());
                    eduEnrollClearCacheHelper.clearCacheMyEnrollPre(vo.getFatherIdcard());
                    eduEnrollClearCacheHelper.clearCacheMyEnrollPre(vo.getMotherIdcard());
                    eduEnrollClearCacheHelper.clearCachePreBefore(vo.getStudentEnrollPreId());
                } else {
                    throw new AppException(schoolVO.getAreaCode() + "未找到处理报名保存的个性化方法");
                }
            } catch (AppException e) {
                throw e;
            } catch (InvocationTargetException e) {
                try {
                    AppException exception = (AppException) e.getTargetException();
                    throw new AppException(exception.getMsg(), e.getTargetException());
                } catch (Exception ex) {
                    throw new AppException(e.getCause().getMessage(), e.getTargetException());
                }

            } catch (Exception e) {
                throw new AppException(e.getMessage());
            }
        } else {
            throw new AppException(schoolVO.getAreaCode() + "未找到处理报名保存的个性化方法");
        }
        return vo;
    }

    @Override
    @OpApi(funcCode = "enrollImitate0005", title = "模拟报名修改", funcType = FuncTypeEnum.update)
    @SaveOplog(
            operationType = "enrollImitate0005",
            operationName = "模拟报名修改",
            dataType = "studentEnrollId",
            auType = AuTypeEnum.OTHER)
    @Transactional
    public EduStudentEnrollVO edit(EduStudentEnrollVO vo) {
        if (StringUtils.isBlank(vo.getStudentEnrollId())) {
            throw new AppException("报名id不能为空");
        }
        if (StringUtils.isBlank(vo.getAuthStatus())) {
            throw new AppException("审核状态不能为空");
        }
        EduStudentEnrollImitate old = eduStudentEnrollService.getById(vo.getStudentEnrollId());
        if (old == null) {
            throw new AppException("报名数据不存在，可能已被退回");
        }
        EduStudentEnrollImitate studentEnroll = Convert.convert(EduStudentEnrollImitate.class, vo);
        //处理传值为false或true时报长度错误
        if (StringUtils.isNotBlank(studentEnroll.getQyFlag())&& studentEnroll.getQyFlag().equalsIgnoreCase("true")) {
            studentEnroll.setQyFlag(BoolEnum.TRUE.getType());
        } else {
            studentEnroll.setQyFlag(BoolEnum.FALSE.getType());
        }
        if (AuthStatusEnum.NODO.getType().equals(studentEnroll.getAuthStatus())) {
            //待审核
            studentEnroll.setAdmitFlag(null);
            studentEnroll.setAdmitTime(null);
            studentEnroll.setEnrollStatus(EnrollStatusFormalEnum.dsh.getType());

        }
        if (AuthStatusEnum.NO.getType().equals(studentEnroll.getAuthStatus())) {
            //审核不通过
            studentEnroll.setAdmitFlag(BoolEnum.FALSE.getType());
            studentEnroll.setEnrollStatus(EnrollStatusFormalEnum.ywblq.getType());
            if (studentEnroll.getAdmitTime() == null) {
                studentEnroll.setAdmitTime(new Date());
            }
            studentEnroll.setAdmitUserId(SessionUtil.getUserId());
        }
        if (AuthStatusEnum.YES.getType().equals(studentEnroll.getAuthStatus())) {
            if (StringUtils.isBlank(studentEnroll.getAdmitFlag()) || "2".equals(studentEnroll.getAdmitFlag())) {
                studentEnroll.setAdmitFlag(null);
                studentEnroll.setAdmitTime(null);
                studentEnroll.setEnrollStatus(EnrollStatusFormalEnum.dlq.getType());
            } else if (BoolEnum.TRUE.getType().equals(studentEnroll.getAdmitFlag())) {
                studentEnroll.setEnrollStatus(EnrollStatusFormalEnum.lq.getType());
                if (studentEnroll.getAdmitTime() == null) {
                    studentEnroll.setAdmitTime(new Date());
                }
            } else {
                studentEnroll.setEnrollStatus(EnrollStatusFormalEnum.ywblq.getType());
                if (studentEnroll.getAdmitTime() == null) {
                    studentEnroll.setAdmitTime(new Date());
                }
            }
        }
        eduStudentEnrollService.updateById(studentEnroll);
        eduEnrollClearCacheHelper.clearCacheMyEnroll(studentEnroll.getIdcard());
        eduEnrollClearCacheHelper.clearCacheMyEnroll(studentEnroll.getFatherIdcard());
        eduEnrollClearCacheHelper.clearCacheMyEnroll(studentEnroll.getMotherIdcard());
        eduEnrollClearCacheHelper.clearCacheMyEnrollPre(studentEnroll.getIdcard());
        eduEnrollClearCacheHelper.clearCacheMyEnrollPre(studentEnroll.getFatherIdcard());
        eduEnrollClearCacheHelper.clearCacheMyEnrollPre(studentEnroll.getMotherIdcard());
        return vo;
    }

    @Override
    @OpApi(funcCode = "enrollImitate0006", title = "模拟报名根据主键删除", funcType = FuncTypeEnum.delete)
    @SaveOplog(
            operationType = "enrollImitate0006",
            operationName = "模拟报名删除",
            dataType = "studentEnrollId",
            auType = AuTypeEnum.OTHER)
    @Transactional
    public void del(EduStudentEnrollKeyVO vo) {
        if (ObjectUtils.isEmpty(vo.getStudentEnrollId())) {
            throw new AppException("传入需要删除的数据主键不能为空!");
        }
        EduStudentEnrollImitate entity = eduStudentEnrollService.getById(vo.getStudentEnrollId());
        if (ObjectUtils.isEmpty(entity)) {
            throw new AppException("未找到需要删除的信息!");
        }
        eduStudentEnrollService.removeById(vo.getStudentEnrollId());
        eduEnrollClearCacheHelper.clearCacheMyEnroll(entity.getIdcard());
        eduEnrollClearCacheHelper.clearCacheMyEnroll(entity.getFatherIdcard());
        eduEnrollClearCacheHelper.clearCacheMyEnroll(entity.getMotherIdcard());
        eduEnrollClearCacheHelper.clearCacheMyEnrollPre(entity.getIdcard());
        eduEnrollClearCacheHelper.clearCacheMyEnrollPre(entity.getFatherIdcard());
        eduEnrollClearCacheHelper.clearCacheMyEnrollPre(entity.getMotherIdcard());
        QueryWrapper<EduStudentEnrollPre> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().select(EduStudentEnrollPre::getStudentEnrollPreId)
                .eq(EduStudentEnrollPre::getIdcard, entity.getIdcard())
                .eq(EduStudentEnrollPre::getYear, entity.getYear());
        EduStudentEnrollPre pre = eduStudentEnrollPreService.getOne(queryWrapper, false);
        if (pre != null) {
            eduEnrollClearCacheHelper.clearCachePreBefore(pre.getStudentEnrollPreId());
        }
    }


    @Override
    public Boolean checkShLq(EnrollCheckShLqVO vo) {
        if (vo.getYear() == null) {
            throw new AppException("年度不能为空");
        }


        int year;
        year = eduHelper.thisYear();

        if (vo.getYear() < year) {
            return true;
        } else if (vo.getYear() > year) {
            return false;
        }
        if (StringUtils.isBlank(vo.getAreaCode())) {
            vo.setAreaCode(SessionUtil.getSessionInfo().getAreaCode());
        }
        if (StringUtils.isBlank(vo.getAreaCode())) {
            throw new AppException("未找到用户所属行政区划,可能是未配置所属组织");
        }
        //EduEnrollPlan eduEnrollPlan = enrollPlanIntegration.getByYear(year);
        EduOperationCacheQueryVO cacheQueryVO = Convert.convert(EduOperationCacheQueryVO.class, vo);
        cacheQueryVO.setClassify("2");
        EduOperationCacheVO eduOperationCacheVO = eduSystemConfigIntegration.getEduOperation(cacheQueryVO);
        if (eduOperationCacheVO.getOperation() == null) {
            throw new AppException(year + "年度招生参数不存在");
        }
        EduOperationCacheDetailVO detailVO = eduOperationCacheVO.getOperation().get("YW064");
        return detailVO.isFlag() || "2".equalsIgnoreCase(detailVO.getType());

    }

    @Override
    @OpApi(funcCode = "enrollImitate0009", title = "查询校验报名情况", funcType = FuncTypeEnum.query)
    public Boolean checkEnroll(YjbmQueryVO vo) {
        EduStudentEnrollPre eduStudentEnrollPre = getPre(vo.getStudentEnrollPreId(), vo.getIdcard());
        if (eduStudentEnrollPre == null) {
            throw new AppException("未找到新生登记信息");
        }
        return this.checkEnroll(eduStudentEnrollPre);
    }

    @Override
    public Boolean checkEnroll(EduStudentEnrollPre eduStudentEnrollPre) {
        return checkEnroll(eduStudentEnrollPre.getIdcard(), eduStudentEnrollPre.getYear());

    }

    @Override
    public Boolean checkEnroll(String idcard, Integer year) {
        if (year == null) {
            EduOperationCacheDetailVO eduOperationCacheDetailVO = operationCacheIntegration.getPeriodYear();
            year = eduOperationCacheDetailVO.getYear();
        }
        List<String> enrollStatusList = new ArrayList<>();
        enrollStatusList.add(EnrollStatusFormalEnum.hy.getType());
        enrollStatusList.add(EnrollStatusFormalEnum.fs.getType());
        enrollStatusList.add(EnrollStatusFormalEnum.dsh.getType());
        enrollStatusList.add(EnrollStatusFormalEnum.dlq.getType());
        enrollStatusList.add(EnrollStatusFormalEnum.lq.getType());
        QueryWrapper<EduStudentEnrollImitate> enrollQueryWrapper = new QueryWrapper<>();
        enrollQueryWrapper.lambda().select(EduStudentEnrollImitate::getIdcard).eq(EduStudentEnrollImitate::getIdcard, idcard)
                .eq(EduStudentEnrollImitate::getYear, year)
                .in(EduStudentEnrollImitate::getEnrollStatus, enrollStatusList);
        if (eduStudentEnrollService.count(enrollQueryWrapper) <= 0) {
            return false;
        }
        return true;
    }

    @Override
    public EduStudentEnrollPre getPre(String studentEnrollPreId, String idcard) {

        if (StringUtils.isNotBlank(studentEnrollPreId)) {
            EduStudentEnrollPre eduStudentEnrollPre =
                    eduStudentEnrollPreService.getById(studentEnrollPreId);
            if (eduStudentEnrollPre == null) {
                throw new AppException("未找到预采集数据");
            }
            if (!AuthStatusEnum.YES.getType().equals(eduStudentEnrollPre.getAuthStatus())) {
                throw new AppException("该预采集未审核或者审核不通过");
            }
            return eduStudentEnrollPre;
        }
        if (StringUtils.isNotBlank(idcard)) {
            Integer year = eduHelper.thisYear();
            QueryWrapper<EduStudentEnrollPre> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().eq(EduStudentEnrollPre::getIdcard, idcard)
                    .eq(EduStudentEnrollPre::getYear, year)
                    .eq(EduStudentEnrollPre::getAuthStatus, AuthStatusEnum.YES.getType());
            List<EduStudentEnrollPre> list = eduStudentEnrollPreService.list(queryWrapper);
            if (CollectionUtils.isEmpty(list)) {
                throw new AppException("未找到有效的学生数据，请先办理准新生登记");
            } else {
                if (list.size() > 1) {
                    throw new AppException("存在多条数据，请联系学校或者技术人员");
                }
                return list.get(0);
            }
        } else {
            throw new AppException("学生身份证或者预采集信息不能为空");
        }

    }

    @Override
    @OpApi(funcCode = "enrollImitate0014", title = "义务教育模拟报名一键退回到待审核", funcType = FuncTypeEnum.update)
    @SaveOplog(
            operationType = "enrollImitate0014",
            operationName = "义务教育模拟报名一键退回到待审核",
            dataType = "studentEnrollId",
            auType = AuTypeEnum.OTHER)
    @Transactional
    public void backAuth(EduStudentEnrollKeyVO vo) {
        EduStudentEnrollImitate old = eduStudentEnrollService.getById(vo.getStudentEnrollId());
        if (old == null) {
            throw new AppException("报名数据不存在，可能已被退回");
        }
        if (EnrollStatusFormalEnum.dsh.getType().equalsIgnoreCase(old.getEnrollStatus()) && AuthStatusEnum.NODO.getType().equals(old.getAuthStatus())) {
            throw new AppException("报名数据已是待审核状态");
        }
        if (EnrollStatusFormalEnum.hy.getType().equalsIgnoreCase(old.getEnrollStatus()) && AuthStatusEnum.NODO.getType().equals(old.getAuthStatus())) {
            throw new AppException("待核验不能退回");
        }
        if (old.getSerialNum() != null) {
            throw new AppException("已摇号数据不能退回到待审核");
        }
        if (StringUtils.isBlank(old.getAreaCode())) {
            old.setAreaCode(SessionUtil.getSessionInfo().getAreaCode());
        }
        EduOperationCacheQueryVO cacheQueryVO = Convert.convert(EduOperationCacheQueryVO.class, old);
        cacheQueryVO.setClassify("2");
        EduOperationCacheVO eduOperationCacheVO = eduSystemConfigIntegration.getEduOperation(cacheQueryVO);
        if (eduOperationCacheVO.getOperation() == null) {
            throw new AppException(old.getYear() + "年度招生计划参数不存在");
        }

        if (eduOperationCacheVO.getOperation().get("YW064") != null) {
            if (!eduOperationCacheVO.getOperation().get("YW064").isFlag()) {
                throw new AppException("只有模拟报名审核期间才能退回");
            }
        }

        if (EnrollStatusFormalEnum.ywblq.getType().equals(old.getEnrollStatus()) || EnrollStatusFormalEnum.xtblq.getType().equals(old.getEnrollStatus())) {
            //从不录取退回到待审核，需要判断其他学校是否审核录取
            List<String> enrollStatusList = new ArrayList<>();
            enrollStatusList.add(EnrollStatusFormalEnum.dlq.getType());
            enrollStatusList.add(EnrollStatusFormalEnum.hy.getType());
            enrollStatusList.add(EnrollStatusFormalEnum.fs.getType());
            enrollStatusList.add(EnrollStatusFormalEnum.lq.getType());
            QueryWrapper<EduStudentEnrollImitate> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().eq(EduStudentEnrollImitate::getYear, old.getYear())
                    .eq(EduStudentEnrollImitate::getIdcard, old.getIdcard())
                    .in(EduStudentEnrollImitate::getEnrollStatus, enrollStatusList)
                    .ne(EduStudentEnrollImitate::getStudentEnrollId, old.getStudentEnrollId());
            if (eduStudentEnrollService.count(queryWrapper) > 0) {
                throw new AppException("因其他学校已审核或录取，这个学校不能从不录取退回到待审核");
            }
        }

        //退回到教育局待复审
        old.setAuthStatus(AuthStatusEnum.NODO.getType());
        old.setAuthRemarks(null);
        old.setAuthTime(null);
        old.setAuthUserId(null);
        old.setAdmitFlag(null);
        old.setAdmitTime(null);
        old.setAdmitUserId(null);
        old.setAdmitRemarks(null);
        old.setEnrollStatus(EnrollStatusFormalEnum.dsh.getType());
        eduStudentEnrollService.updateById(old);
        eduEnrollClearCacheHelper.clearCacheMyEnroll(old.getIdcard());
        eduEnrollClearCacheHelper.clearCacheMyEnroll(old.getFatherIdcard());
        eduEnrollClearCacheHelper.clearCacheMyEnroll(old.getMotherIdcard());
    }

    @Override
    @OpApi(funcCode = "enrollImitate0015", title = "义务教育模拟管理端报名退回", funcType = FuncTypeEnum.update)
    @SaveOplog(
            operationType = "enrollImitate0015",
            operationName = "义务教育模拟管理端报名退回",
            dataType = "studentEnrollId",
            auType = AuTypeEnum.OTHER)
    @Transactional
    public void ywApplyBack(EduStudentEnrollKeyVO vo) {
        EduStudentEnrollImitate studentEnroll = eduStudentEnrollService.getById(vo.getStudentEnrollId());
        if (!StringUtils.equals(studentEnroll.getAuthStatus(), AuthStatusEnum.NODO.getType())) {
            throw new AppException("当前人员已审核，不允许退回");
        }

        QueryWrapper<EduStudentEnrollImitate> shlqQuery = new QueryWrapper<>();
        shlqQuery.lambda().select(EduStudentEnrollImitate::getStudentEnrollId)
                .eq(EduStudentEnrollImitate::getIdcard, studentEnroll.getIdcard())
                .eq(EduStudentEnrollImitate::getYear, studentEnroll.getYear())
                .ne(EduStudentEnrollImitate::getEnrollStatus, EnrollStatusFormalEnum.dsh.getType());
        if (eduStudentEnrollService.count(shlqQuery) > 0) {
            throw new AppException("已有学校已审核，不能退回");
        }

        eduStudentEnrollService.removeById(vo.getStudentEnrollId());
        eduEnrollClearCacheHelper.clearCacheMyEnroll(studentEnroll.getIdcard());
        eduEnrollClearCacheHelper.clearCacheMyEnroll(studentEnroll.getFatherIdcard());
        eduEnrollClearCacheHelper.clearCacheMyEnroll(studentEnroll.getMotherIdcard());
        eduEnrollClearCacheHelper.clearCacheMyEnrollPre(studentEnroll.getIdcard());
        eduEnrollClearCacheHelper.clearCacheMyEnrollPre(studentEnroll.getFatherIdcard());
        eduEnrollClearCacheHelper.clearCacheMyEnrollPre(studentEnroll.getMotherIdcard());
        String bmKey = EduCache.EDU_ENROLL_MN + studentEnroll.getIdcard();
        redisHelper.del(bmKey);
    }

    @Override
    @OpApi(funcCode = "enrollImitate0063", title = "家长端义务教育模拟报名撤销", funcType = FuncTypeEnum.update)
    @SaveOplog(
            operationType = "enrollImitate0063",
            operationName = "家长端义务教育模拟报名撤销",
            dataType = "studentEnrollId",
            auType = AuTypeEnum.OTHER)
    @Transactional
    public void ywApplyBackApp(EduStudentEnrollKeyVO vo) {

        EduStudentEnrollImitate studentEnroll = eduStudentEnrollService.getById(vo.getStudentEnrollId());
        if (!StringUtils.equals(studentEnroll.getAuthStatus(), AuthStatusEnum.NODO.getType())) {
            throw new AppException("当前人员已审核，不允许撤销");
        }
        if (!SessionUtil.getUserId().equalsIgnoreCase(studentEnroll.getCreateName())) {
            throw new AppException("只能通过报名账号才能进行撤销");
        }
        EduOperationCacheQueryVO queryVO = new EduOperationCacheQueryVO();
        queryVO.setClassify("2");
        queryVO.setAreaCode(studentEnroll.getAreaCode());
        queryVO.setYear(studentEnroll.getYear());
        EduOperationCacheVO eduOperationCacheVO = eduSystemConfigIntegration.getEduOperation(queryVO);
        Map<String, EduOperationCacheDetailVO> operation = eduOperationCacheVO.getOperation();
        EduOperationCacheDetailVO bmOperation = operation.get("YW062");//报名时间
        //判断是否报名业务期
        boolean bmFlag = bmOperation == null ? false : bmOperation.isFlag();

        if (!bmFlag) {
            throw new AppException("报名时间已过不能撤销");
        }
        LambdaQueryWrapper<EduStudentEnrollPre> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.select(EduStudentEnrollPre::getStudentEnrollPreId).eq(EduStudentEnrollPre::getYear,studentEnroll.getYear())
                        .eq(EduStudentEnrollPre::getIdcard,studentEnroll.getIdcard());
        List<EduStudentEnrollPre> preList=eduStudentEnrollPreService.list(queryWrapper);
        if(!CollectionUtils.isEmpty(preList)){
            for(EduStudentEnrollPre pre:preList){
                eduEnrollClearCacheHelper.clearCachePreBefore(pre.getStudentEnrollPreId());
            }
        }
        eduStudentEnrollService.removeById(vo.getStudentEnrollId());
        eduEnrollClearCacheHelper.clearCacheMyEnroll(studentEnroll.getIdcard());
        eduEnrollClearCacheHelper.clearCacheMyEnroll(studentEnroll.getFatherIdcard());
        eduEnrollClearCacheHelper.clearCacheMyEnroll(studentEnroll.getMotherIdcard());
        eduEnrollClearCacheHelper.clearCacheMyEnrollPre(studentEnroll.getIdcard());
        eduEnrollClearCacheHelper.clearCacheMyEnrollPre(studentEnroll.getFatherIdcard());
        eduEnrollClearCacheHelper.clearCacheMyEnrollPre(studentEnroll.getMotherIdcard());


        String bmKey = EduCache.EDU_ENROLL_MN + studentEnroll.getIdcard();
        redisHelper.del(bmKey);
    }

    @Override
    @OpApi(funcCode = "enrollImitate0016", title = "义务教育模拟报名修改报名状态", funcType = FuncTypeEnum.update)
    @SaveOplog(
            operationType = "enrollImitate0016",
            operationName = "义务教育模拟报名修改报名状态",
            dataType = "studentEnrollId",
            auType = AuTypeEnum.OTHER)
    @Transactional
    public void updateEnrollStatus(UpdateEnrollStatusVO vo) {
        if (StringUtils.isBlank(vo.getStudentEnrollId())) {
            throw new AppException("报名id不能为空");
        }
        if (StringUtils.isBlank(vo.getEnrollStatus())) {
            throw new AppException("报名状态不能为空");
        }
        EduStudentEnrollImitate old = eduStudentEnrollService.getById(vo.getStudentEnrollId());
        if (old == null) {
            throw new AppException("报名数据不存在，可能已被退回");
        }
        if (old.getEnrollStatus().equals(vo.getEnrollStatus())) {
            throw new AppException("报名状态和数据库中一致，请刷新后再操作");
        }

        old.setEnrollStatus(vo.getEnrollStatus());
        eduStudentEnrollService.updateById(old);

        eduEnrollClearCacheHelper.clearCacheMyEnroll(old.getIdcard());
        eduEnrollClearCacheHelper.clearCacheMyEnroll(old.getFatherIdcard());
        eduEnrollClearCacheHelper.clearCacheMyEnroll(old.getMotherIdcard());
        eduEnrollClearCacheHelper.clearCacheMyEnrollPre(old.getIdcard());
        eduEnrollClearCacheHelper.clearCacheMyEnrollPre(old.getFatherIdcard());
        eduEnrollClearCacheHelper.clearCacheMyEnrollPre(old.getMotherIdcard());
    }

    @Override
    @OpApi(funcCode = "enrollImitate0043", title = "义务教育模拟报名审核", funcType = FuncTypeEnum.update)
    @SaveOplog(
            operationType = "enrollImitate0043",
            operationName = "义务教育模拟报名审核",
            dataType = "studentEnrollId",
            auType = AuTypeEnum.OTHER)
    @Transactional
    public void ywAudit(StudentEnrollSaveVO vo) {
        if (StringUtils.isBlank(vo.getStudentEnrollId())) {
            throw new AppException("报名id不能为空");
        }
        if (StringUtils.isBlank(vo.getAuthStatus())) {
            throw new AppException("审核状态不能为空");
        }
        if (StringUtils.isBlank(vo.getAreaCode())) {
            vo.setAreaCode(SessionUtil.getSessionInfo().getAreaCode());
        }


        EduStudentEnrollImitate old = eduStudentEnrollService.getById(vo.getStudentEnrollId());
        if (old == null) {
            throw new AppException("报名数据不存在，可能已被回退，请重新查询");
        }
        if (old.getEnrollStatus().equals(EnrollStatusFormalEnum.hy.getType())) {
            throw new AppException("线下核验未审核通过,不能进行初审");
        }
        if (old.getEnrollStatus().equals(EnrollStatusFormalEnum.dlq.getType())) {
            throw new AppException("初审通过，不能重复审核");
        }
        if (old.getEnrollStatus().equals(EnrollStatusFormalEnum.fs.getType())) {
            throw new AppException("复审通过，不能进行初审");
        }
        if (old.getEnrollStatus().equals(EnrollStatusFormalEnum.lq.getType())) {
            throw new AppException("已录取，不能进行初审");
        }
        int year;
        year = eduHelper.thisYear();

        if (old.getYear() < year) {
            throw new AppException("历年报名数据不允许审核");
        }


        //业务期判断
        EnrollCheckShLqVO checkShLqVO = new EnrollCheckShLqVO();
        checkShLqVO.setSchoolId(old.getSchoolId());
        checkShLqVO.setYear(old.getYear());
        checkShLqVO.setAreaCode(old.getAreaCode());
        if ("0".equals(old.getSchoolNature()) || "2".equals(old.getSchoolNature())) {
            checkShLqVO.setOpType(old.getSchoolNature());
        }
        if ("1".equals(old.getSchoolNature())) {
            if ("1".equals(old.getAspirationType())) {
                //民办1
                checkShLqVO.setOpType("1");
            }
            if ("2".equals(old.getAspirationType())) {
                //民办2
                checkShLqVO.setOpType("3");
            }
            if ("3".equals(old.getAspirationType())) {
                //民办3
                checkShLqVO.setOpType("4");
            }

        }
        checkSh(checkShLqVO);

        if (!AuthStatusEnum.NODO.getType().equals(old.getAuthStatus())) {
            throw new AppException(old.getFullName() + "的报名数据已审核，请重新查询");
        }
        if (!old.getSchoolId().equals(SessionUtil.getSessionInfo().getOrgId())) {
            throw new AppException("报名学校和审核学校不一致，请联系管理员查找原因");
        }

        QueryWrapper<EduEnrollmenBrochure> queryBrochureWrapper = new QueryWrapper<>();
        queryBrochureWrapper.lambda().eq(EduEnrollmenBrochure::getYear, old.getYear())
                .eq(EduEnrollmenBrochure::getSchoolId, old.getSchoolId());
        EduEnrollmenBrochure eduEnrollmenBrochure = eduEnrollmenBrochureService.getOne(queryBrochureWrapper, false);
        if (eduEnrollmenBrochure == null) {
            throw new AppException("未找到招生方案信息");
        }

        if (BoolEnum.TRUE.getType().equals(eduEnrollmenBrochure.getEndRegistration())) {
            throw new AppException("招生已停止，不能审核");
        }

        List<String> enrollStatusList = new ArrayList<>();
        enrollStatusList.add(EnrollStatusFormalEnum.hy.getType());
        enrollStatusList.add(EnrollStatusFormalEnum.dlq.getType());
        enrollStatusList.add(EnrollStatusFormalEnum.lq.getType());
        enrollStatusList.add(EnrollStatusFormalEnum.fs.getType());
        QueryWrapper<EduStudentEnrollImitate> enrollQueryWrapper = new QueryWrapper<>();
        enrollQueryWrapper.lambda().select(EduStudentEnrollImitate::getStudentEnrollId)
                .eq(EduStudentEnrollImitate::getIdcard, old.getIdcard())
                .in(EduStudentEnrollImitate::getEnrollStatus, enrollStatusList)
                .ne(EduStudentEnrollImitate::getSchoolId, old.getSchoolId());
        if (eduStudentEnrollService.count(enrollQueryWrapper) > 0) {
            throw new AppException(old.getFullName() + "，其他学校资料审核通过或者已录取");
        }
        old.setAuthTime(new Date());
        old.setAuthRemarks(vo.getAuthRemarks());
        old.setAuthUserId(SessionUtil.getSessionInfo().getUserId());
        old.setAuthRemarks(vo.getAuthRemarks());

        old.setAuthStatus(vo.getAuthStatus());
        old.setAuthTime(new Date());

        old.setAuthUserId(SessionUtil.getSessionInfo().getUserId());
        if(StringUtils.isNotBlank(vo.getAuthRemarks())){
            old.setAuthRemarks(vo.getAuthRemarks());
        }else{
            if (AuthStatusEnum.NO.getType().equals(vo.getAuthStatus())) {
                old.setAuthRemarks("审核不通过");
                old.setEnrollStatus(EnrollStatusFormalEnum.ywblq.getType());
            }else{
                old.setAuthRemarks("审核通过");
                old.setEnrollStatus(EnrollStatusFormalEnum.dlq.getType());
            }
        }

        eduStudentEnrollService.updateById(old);
        eduEnrollClearCacheHelper.clearCacheMyEnroll(old.getIdcard());
        eduEnrollClearCacheHelper.clearCacheMyEnroll(old.getFatherIdcard());
        eduEnrollClearCacheHelper.clearCacheMyEnroll(old.getMotherIdcard());
    }

    @Override
    @OpApi(funcCode = "enrollImitate00044", title = "模拟报名线下核验材料查询", funcType = FuncTypeEnum.query)
    public List<EduStudentEnrollVerificationVO> getVerification(EduStudentEnrollVerificationVO vo) {
        LambdaQueryWrapper<EduStudentEnrollVerification> queryWrapper = new QueryWrapper<EduStudentEnrollVerification>()
                .lambda().eq(EduStudentEnrollVerification::getStudentEnrollId, vo.getStudentEnrollId());
        List<EduStudentEnrollVerification> verificationList = eduStudentEnrollVerificationService.list(queryWrapper);
        List<EduStudentEnrollVerificationVO> result = Convert.toList(EduStudentEnrollVerificationVO.class, verificationList);
        dictHelper.valueToName(result, Arrays.asList(VerificationEnum.values()));
        return result;
    }

    @Override
    @OpApi(funcCode = "enrollImitate00045", title = "模拟报名线下核验材料核验", funcType = FuncTypeEnum.update)
    @SaveOplog(
            operationType = "enrollImitate00045",
            operationName = "模拟报名线下核验材料核验",
            dataType = "studentEnrollId",
            auType = AuTypeEnum.OTHER)
    @Transactional
    public void verificationAudit(EduStudentEnrollVerificationVO vo) {
        if (StringUtils.isBlank(vo.getStudentEnrollId())) {
            throw new AppException("报名id不能为空");
        }
        if (StringUtils.isBlank(vo.getAreaCode())) {
            vo.setAreaCode(SessionUtil.getSessionInfo().getAreaCode());
        }
        EduStudentEnrollImitate old = eduStudentEnrollService.getById(vo.getStudentEnrollId());
        if (old == null) {
            throw new AppException("报名数据不存在，可能已被回退，请重新查询");
        }
        int year;
        year = eduHelper.thisYear();
        if (old.getYear() < year) {
            throw new AppException("历年报名数据不允许核验");
        }
        if (BoolEnum.FALSE.getType().equalsIgnoreCase(old.getIcertificatioFlag())) {
            //待核验
            throw new AppException("该人员不需要核验，请刷新数据");
        }
        if (!BoolEnum.TRUE.getType().equalsIgnoreCase(old.getIcertificatioFlag())) {
            //待核验
            throw new AppException("该数据已核验，请查看核验结果");
        }
        if (!CollectionUtils.isEmpty(vo.getVerificationVOList())) {
            ArrayList<EduStudentEnrollVerification> list = new ArrayList<>();
            UpdateWrapper<EduStudentEnrollPre> preUpdateWrapper = new UpdateWrapper<>();
            preUpdateWrapper.lambda().eq(EduStudentEnrollPre::getIdcard, old.getIdcard())
                    .eq(EduStudentEnrollPre::getYear, old.getYear());
            boolean updateFlag = false;
            for (EduStudentEnrollVerificationVO ver : vo.getVerificationVOList()) {
                ver.setVerificationUserId(SessionUtil.getUserId());
                ver.setVerificationTime(new Date());
                EduStudentEnrollVerification verification = Convert.convert(EduStudentEnrollVerification.class, ver);
                list.add(verification);
                if (BoolEnum.TRUE.getType().equalsIgnoreCase(ver.getVerificationStatus())) {
                    //核验通过
                    if (VerificationTypeEnum.yzb.getType().equalsIgnoreCase(ver.getVerificationType())
                            || VerificationTypeEnum.fwq.getType().equalsIgnoreCase(ver.getVerificationType())
                            || VerificationTypeEnum.fhyz.getType().equalsIgnoreCase(ver.getVerificationType())) {
                        preUpdateWrapper.lambda().set(EduStudentEnrollPre::getHouseId, old.getHouseId())
                                .set(EduStudentEnrollPre::getHouseholdId, old.getHouseholdId())
                                .set(EduStudentEnrollPre::getConsistentType, "2")//人工核对
                                .set(EduStudentEnrollPre::getConsistentFlag, BoolEnum.TRUE.getType())
                                .set(EduStudentEnrollPre::getConsistentRemarks, "报名后线下人工核验")
                                .set(EduStudentEnrollPre::getConsistentTime, new Date())
                                .set(EduStudentEnrollPre::getConsistentUserId, SessionUtil.getUserId());
                        updateFlag = true;
                    }
                    if (VerificationTypeEnum.yzb.getType().equalsIgnoreCase(ver.getVerificationType())) {
                        preUpdateWrapper.lambda().set(EduStudentEnrollPre::getAborigineFlag, BoolEnum.TRUE.getType());
                    }
                    if (VerificationTypeEnum.fwq.getType().equalsIgnoreCase(ver.getVerificationType())) {
                        preUpdateWrapper.lambda().set(EduStudentEnrollPre::getServiceAreaFlag, BoolEnum.TRUE.getType());
                    }
                    if (VerificationTypeEnum.qzgx.getType().equalsIgnoreCase(ver.getVerificationType())) {
                        preUpdateWrapper.lambda().set(EduStudentEnrollPre::getFamilyFlag, BoolEnum.TRUE.getType())
                                .set(EduStudentEnrollPre::getFamilyType, "2")
                                .set(EduStudentEnrollPre::getFamilyRemark, "报名后线下人工核验");
                        updateFlag = true;
                    }
                }
            }
            if (updateFlag) {
                eduStudentEnrollPreService.update(preUpdateWrapper);
            }
            UpdateWrapper<EduStudentEnrollImitate> updateWrapper = new UpdateWrapper<EduStudentEnrollImitate>();
            if (vo.getIcertificatioFlag().equals(VerificationAuthStatusEnum.hybtg.getType())){
                //当核验不通过时：enrollStatus 设置为7 审核状态设置为审核不通过,录取状态设置为0 不予录取
                updateWrapper.lambda().set(EduStudentEnrollImitate::getEnrollStatus,EnrollStatusFormalEnum.hy.getType())
                        .set(EduStudentEnrollImitate::getAuthStatus,AuthStatusEnum.NO.getType())
                        .set(EduStudentEnrollImitate::getAdmitFlag,BoolEnum.FALSE.getType());
            }
            if (vo.getIcertificatioFlag().equals(VerificationAuthStatusEnum.hytg.getType())){
                updateWrapper.lambda().set(EduStudentEnrollImitate::getEnrollStatus,EnrollStatusFormalEnum.dsh.getType());
            }
            updateWrapper.lambda().set(EduStudentEnrollImitate::getIcertificatioFlag, vo.getIcertificatioFlag())
                    .eq(EduStudentEnrollImitate::getStudentEnrollId, old.getStudentEnrollId());
            eduStudentEnrollService.update(updateWrapper);
            eduStudentEnrollVerificationService.updateBatchById(list);
        }
    }

    @Override
    @OpApi(funcCode = "enrollImitate0013", title = "获取义务教育模拟报名单个明细", funcType = FuncTypeEnum.query)
    public EduStudentEnrollVO getYwApplyDetail(EduStudentEnrollKeyVO vo) {
        return this.getYwApplyById(vo);
    }

    @Override
    public EduStudentEnrollVO getYwApplyById(EduStudentEnrollKeyVO vo) {
        String studentEnrollId = vo.getStudentEnrollId();
        Assert.hasText(studentEnrollId, "义务教育学生报名id不能为空");
        EduStudentEnrollQueryVO queryVO = new EduStudentEnrollQueryVO();
        queryVO.setStudentEnrollId(studentEnrollId);
        List<EduStudentEnrollVO> list = eduStudentEnrollService.getYwApplyList(queryVO);
        if (CollectionUtils.isEmpty(list)) {
            throw new AppException("未找到报名信息，请刷新页面后重新再试");
        }
        EduStudentEnrollVO studentEnrollVO = Convert.convert(EduStudentEnrollVO.class, list.get(0));
        List<String> areaCodeList = new ArrayList<>();
        //获取当前部署行政区划

        DictAreaVO dictAreaVO = new DictAreaVO();
        List<SelectVO> districtByOrg = dictIntegration.getDistrictByOrg(dictAreaVO);
        if (!CollectionUtils.isEmpty(districtByOrg)) {
            areaCodeList = districtByOrg.stream().map(SelectVO::getDictKey).distinct().collect(Collectors.toList());
        } else {
            areaCodeList.add(studentEnrollVO.getAreaCode());
        }

        /*
         * source:6 学校录入报名数据
         * */
        if (StringUtils.isNotEmpty(studentEnrollVO.getSource())) {
            if ("6".equals(studentEnrollVO.getSource())) {
                studentEnrollVO.setFileInfo(studentEnrollVO.getParam20());
            }
        }

        String formId = studentEnrollVO.getFormId();
        if ("0".equals(studentEnrollVO.getSchoolNature())
                &&!BoolEnum.TRUE.getType().equals(studentEnrollVO.getSpecialFlag())
                &&!"直升".equals(studentEnrollVO.getConfigName())
                && ObjectUtils.isEmpty(formId)) {
            throw new AppException("数据异常：报名表单id为空，请联系系统管理员");
        }
        EduStudentEnroll gbEnroll = null;

        if ("0".equals(studentEnrollVO.getSchoolNature())) {
            gbEnroll = Convert.convert(EduStudentEnroll.class, studentEnrollVO);
        }


        int year = studentEnrollVO.getYear();
        List<EduFormEnrollParams> configList = null;
        if (gbEnroll != null) {
            if (BoolEnum.TRUE.getType().equals(gbEnroll.getSpecialFlag())) {
                //特殊通道
                QueryWrapper<EduFormSpecialParams> configQueryWrapper = new QueryWrapper<>();
                configQueryWrapper.lambda().eq(EduFormSpecialParams::getFormSpecialId, formId);
                List<EduFormSpecialParams> formSpecialList = eduFormSpecialParamsService.list(configQueryWrapper);
                if (!CollectionUtils.isEmpty(formSpecialList)) {
                    configList = Convert.toList(EduFormEnrollParams.class, formSpecialList);
                }
            } else {
                QueryWrapper<EduFormEnrollParams> configQueryWrapper = new QueryWrapper<>();
                configQueryWrapper.lambda().eq(EduFormEnrollParams::getFormId, formId);
                configList = eduFormEnrollParamsService.list(configQueryWrapper);
            }
        }

        studentEnrollVO.setXjFlag(false);
        studentEnrollVO.setSbFlag(false);
        studentEnrollVO.setHjFlag(false);
        studentEnrollVO.setFcFlag(false);
        studentEnrollVO.setQyFlag(false);
        studentEnrollVO.setJzzFlag(false);
        studentEnrollVO.setWqFlag(false);
        studentEnrollVO.setHjDsjFlag(false);
        studentEnrollVO.setFcDsjFlag(false);
        List<EduFormEnrollParamsVO> formConfigVOList = new ArrayList<>();
        List<String> idcardList = new ArrayList<>();
        if (gbEnroll != null && "0".equals(gbEnroll.getSchoolNature())) {
            idcardList.add(gbEnroll.getIdcard());
            if (StringUtils.isNotBlank(gbEnroll.getFatherIdcard())) {
                idcardList.add(gbEnroll.getFatherIdcard());
            }
            if (StringUtils.isNotBlank(gbEnroll.getMotherIdcard())) {
                idcardList.add(gbEnroll.getMotherIdcard());
            }
            //公办学校处理
            if ("A".equals(gbEnroll.getConfigName())) {
                studentEnrollVO.setHjFlag(true);
                studentEnrollVO.setFcFlag(true);
            }
            if ("B".equals(gbEnroll.getConfigName())) {
                studentEnrollVO.setHjFlag(true);
            }
            if ("C".equals(gbEnroll.getConfigName())) {
                studentEnrollVO.setFcFlag(true);
            }
            if ("特殊户口".equals(gbEnroll.getConfigName())) {
                studentEnrollVO.setHjFlag(true);
            }
            if ("E".equals(gbEnroll.getConfigName()) && BoolEnum.TRUE.getType().equalsIgnoreCase(gbEnroll.getAppointFlag())) {
                studentEnrollVO.setXjFlag(true);
            }

            if (!CollectionUtils.isEmpty(configList)) {
                configList.forEach(item -> {
                    if (StringUtils.equals(item.getPropertyType(), "4")) {
                        studentEnrollVO.setXjFlag(true);
                    } else if (StringUtils.equals(item.getPropertyType(), "5")) {
                        studentEnrollVO.setHjFlag(true);
                    } else if (StringUtils.equals(item.getPropertyType(), "6")) {
                        studentEnrollVO.setFcFlag(true);

                    } else if (StringUtils.equals(item.getPropertyType(), "7")) {
                        studentEnrollVO.setWqFlag(true);

                    } else if (StringUtils.equals(item.getPropertyType(), "8")) {

                        studentEnrollVO.setSbFlag(true);

                    } else if (StringUtils.equals(item.getPropertyType(), "9")) {

                        studentEnrollVO.setQyFlag(true);

                    } else if (StringUtils.equals(item.getPropertyType(), "10")) {

                        studentEnrollVO.setJzzFlag(true);

                    } else {
                        formConfigVOList.add(Convert.convert(EduFormEnrollParamsVO.class, item));
                    }
                });

            }

            if (studentEnrollVO.getWqFlag()) {
                //网签
                if (StringUtils.isNotBlank(gbEnroll.getNetsignId())) {
                    QueryWrapper<EduNetsign> netsignQueryWrapper = new QueryWrapper<>();
                    netsignQueryWrapper.lambda().eq(EduNetsign::getYear, year)
                            .eq(EduNetsign::getNetsignId, gbEnroll.getNetsignId())
                            .orderByAsc(EduNetsign::getBasj);
                    List<EduNetsign> netsignList = eduNetsignService.list(netsignQueryWrapper);
                    if (!CollectionUtils.isEmpty(netsignList)) {
                        List<EduNetsignVO> netsignVOList = Convert.toList(EduNetsignVO.class, netsignList);
                        for (EduNetsignVO eduNetsignVO : netsignVOList) {
                            if (StringUtils.isNotBlank(eduNetsignVO.getSchoolId())) {
                                EduSchoolVO eduSchool = eduSchoolService.getDetail(eduNetsignVO.getSchoolId());
                                if (eduSchool != null) {
                                    eduNetsignVO.setSchoolName(eduSchool.getSchoolName());
                                }
                            }
                        }
                        studentEnrollVO.setWqList(netsignVOList);
                    }
                }
            }
            if (studentEnrollVO.getSbFlag()) {
                //社保
                if (StringUtils.isNotBlank(gbEnroll.getSocialSecurityId())) {
                    QueryWrapper<EduSocialSecurity> securityQueryWrapper = new QueryWrapper<>();
                    securityQueryWrapper.lambda().eq(EduSocialSecurity::getYear, year)
                            .eq(EduSocialSecurity::getAab301, gbEnroll.getAreaCode())
                            .in(EduSocialSecurity::getAac147, idcardList)
                            .eq(EduSocialSecurity::getAac031, "1")
                            .eq(EduSocialSecurity::getAac008, "1")
                            .orderByAsc(EduSocialSecurity::getAac147).orderByAsc(EduSocialSecurity::getAae140).orderByAsc(EduSocialSecurity::getAae030);
                    List<EduSocialSecurity> socialSecurityList = eduSocialSecurityService.list(securityQueryWrapper);
                    if (!CollectionUtils.isEmpty(socialSecurityList)) {
                        List<EduSocialSecurityVO> cbVOList = Convert.toList(EduSocialSecurityVO.class, socialSecurityList);
                        for (EduSocialSecurityVO eduSocialSecurityVO : cbVOList) {
                            if ("1".equalsIgnoreCase(eduSocialSecurityVO.getAac008())) {
                                if ("1".equalsIgnoreCase(eduSocialSecurityVO.getAac031())) {
                                    eduSocialSecurityVO.setStatus("1");
                                    eduSocialSecurityVO.setStatusName("正常参保");
                                } else {
                                    eduSocialSecurityVO.setStatus("2");
                                    eduSocialSecurityVO.setStatusName("参保中断");
                                }
                            } else {
                                eduSocialSecurityVO.setStatus("3");
                                eduSocialSecurityVO.setStatusName("参保终止");
                            }
                        }

                        studentEnrollVO.setSbList(cbVOList);
                    }
                }
            }
            if (studentEnrollVO.getQyFlag()) {
                //企业
                if (StringUtils.isNotBlank(gbEnroll.getCompanyId())) {
                    QueryWrapper<EduCompany> companyQueryWrapper = new QueryWrapper<>();
                    companyQueryWrapper.lambda().eq(EduCompany::getYear, year)
                            .eq(EduCompany::getCompanyId, gbEnroll.getCompanyId());
                    List<EduCompany> companyList = eduCompanyService.list(companyQueryWrapper);
                    if (!CollectionUtils.isEmpty(companyList)) {
                        List<CompanyVO> qyVOList = Convert.toList(CompanyVO.class, companyList);
                        studentEnrollVO.setQyList(qyVOList);
                    }
                }
            }
            if (studentEnrollVO.getJzzFlag()) {
                //居住证
                if (StringUtils.isNotBlank(gbEnroll.getLivePlaceId())) {
                    QueryWrapper<EduLivePlace> livePlaceQueryWrapper = new QueryWrapper<>();
                    livePlaceQueryWrapper.lambda().eq(EduLivePlace::getYear, year)
                            .eq(EduLivePlace::getLivePlaceId, gbEnroll.getLivePlaceId()).orderByAsc(EduLivePlace::getSfzh);
                    List<EduLivePlace> livePlaceList = eduLivePlaceService.list(livePlaceQueryWrapper);
                    if (!CollectionUtils.isEmpty(livePlaceList)) {
                        List<LivePlaceVO> livePlaceVOList = Convert.toList(LivePlaceVO.class, livePlaceList);
                        studentEnrollVO.setJzzList(livePlaceVOList);
                    }
                }
            }
            if (studentEnrollVO.getXjFlag()) {
                //学籍
                if (StringUtils.isNotBlank(gbEnroll.getStudentStatusId())) {
                    EduStudentStatus studentStatus = eduStudentStatusService.getById(gbEnroll.getStudentStatusId());
                    if (studentStatus != null) {
                        studentEnrollVO.setXjInfo(
                                Convert.convert(StudentStatusVO.class, studentStatus));
                    }

                } else {
                    QueryWrapper<EduStudentStatus> statusQueryWrapper = new QueryWrapper<>();
                    statusQueryWrapper.lambda().eq(EduStudentStatus::getYear, gbEnroll.getYear())
                            .eq(EduStudentStatus::getIdcard, gbEnroll.getIdcard());
                    List<EduStudentStatus> studentStatusList = eduStudentStatusService.list(statusQueryWrapper);
                    if (!CollectionUtils.isEmpty(studentStatusList)) {
                        studentEnrollVO.setXjInfo(
                                Convert.convert(StudentStatusVO.class, studentStatusList.get(0)));
                    }
                }
            }
            if (studentEnrollVO.getFcFlag()) {
                //房产
                if (StringUtils.isNotBlank(gbEnroll.getHouseId())) {
                    EduHouse eduHouse = eduHouseService.getHouseById(gbEnroll.getHouseId());
                    //数据为空去查询历史表
                    if (ObjectUtils.isEmpty(eduHouse)) {
                        EduhHouse eduhHouse = eduhHouseService.getById(gbEnroll.getHouseId());
                        if (eduhHouse != null && eduhHouse.getStatus().equals(BoolEnum.TRUE.getType()) && eduhHouse.getAuthStatus().equals(AuthStatusEnum.YES.getType())) {
                            //判断是否加密过
                            if (EduStatusTypeEnum.success.getType().equals(eduhHouse.getEncryptFlag())) {
                                eduhHouseService.decrypt(eduhHouse);
                            }
                            studentEnrollVO.setFcInfo(
                                    Convert.convert(EduHouseVO.class, eduhHouse));
                        }
                    }
                    if (eduHouse != null && eduHouse.getStatus().equals(BoolEnum.TRUE.getType()) && eduHouse.getAuthStatus().equals(AuthStatusEnum.YES.getType())) {
                        studentEnrollVO.setFcInfo(
                                Convert.convert(EduHouseVO.class, eduHouse));
                    }
                }
            }
            if (studentEnrollVO.getHjFlag()) {
                //户籍
                if (StringUtils.isNotBlank(gbEnroll.getHouseholdId())) {
                    EduHousehold eduHousehold = eduHouseholdService.getHouseholdById(gbEnroll.getHouseholdId());
                    if (eduHousehold != null && eduHousehold.getStatus().equals(BoolEnum.TRUE.getType())) {
                        studentEnrollVO.setHjInfo(
                                Convert.convert(EduHouseholdVO.class, eduHousehold));
                    }
                }
            }

        }

        studentEnrollVO.setParamsVOList(formConfigVOList);

        //查询户籍信息

        boolean houseHoldFlag = false;
        if (SchoolNatureEnum.mb.getType().equalsIgnoreCase(studentEnrollVO.getSchoolNature())) {
            if (StringUtils.isBlank(studentEnrollVO.getHouseholdAddress())) {
                houseHoldFlag = true;
            }
            if (!BoolEnum.TRUE.getType().equalsIgnoreCase(studentEnrollVO.getFollowingFlag())) {
                houseHoldFlag = true;
            }
        }
        if (houseHoldFlag) {
            QueryWrapper<EduHousehold> householdQueryWrapper = new QueryWrapper<>();
            householdQueryWrapper.lambda().select(EduHousehold::getAddress).eq(EduHousehold::getIdcard, studentEnrollVO.getIdcard())
                    .eq(EduHousehold::getAreaCode, studentEnrollVO.getAreaCode())
                    .in(EduHousehold::getAreaCode, areaCodeList)
                    .eq(EduHousehold::getYear, studentEnrollVO.getYear())
                    .eq(EduHousehold::getStatus, BoolEnum.TRUE.getType());
            List<EduHousehold> householdList = eduHouseholdService.list(householdQueryWrapper);
            if (!CollectionUtils.isEmpty(householdList)) {
                studentEnrollVO.setHasHousehold(true);
                studentEnrollVO.setFollowingFlag(BoolEnum.TRUE.getType());
                if (StringUtils.isBlank(studentEnrollVO.getHouseholdAddress())) {
                    studentEnrollVO.setHouseholdAddress(householdList.get(0).getAddress());
                }
            } else {
                studentEnrollVO.setHasHousehold(false);
            }
        }
        QueryWrapper<EduStudentEnrollVerification> queryVWrapper = new QueryWrapper<>();
        queryVWrapper.lambda().eq(EduStudentEnrollVerification::getStudentEnrollId, studentEnrollVO.getStudentEnrollId());
        List<EduStudentEnrollVerification> verificationList = eduStudentEnrollVerificationService.list(queryVWrapper);
        if (!CollectionUtils.isEmpty(list)){
            if (!studentEnrollVO.getIcertificatioFlag().equals(BoolEnum.FALSE.getType())) {
                studentEnrollVO.setHyFlag(true);
            }
            if (!CollectionUtils.isEmpty(verificationList)){
                List<EduStudentEnrollVerificationVO> verificationVOList = Convert.toList(EduStudentEnrollVerificationVO.class, verificationList);
                dictHelper.valueToName(verificationVOList, Arrays.asList(VerificationEnum.values()));
                //遍历核验数据，根据核验类型设置核验材料列表
                for (EduStudentEnrollVerificationVO enrollVerification : verificationVOList) {
                    setVerificationMaterial(enrollVerification,studentEnrollVO);
                }
                studentEnrollVO.setVerificationVOList(verificationVOList);
            }else{
                studentEnrollVO.setVerificationVOList(new ArrayList<>());
            }
        }else{
            studentEnrollVO.setVerificationVOList(new ArrayList<>());
        }
        Integer thisYear = eduHelper.thisYear();
        Boolean desensitizeFlag = vo.getDesensitizeFlag();
        if (desensitizeFlag == null) {
            if (thisYear - studentEnrollVO.getYear() == 0) {
                EduOperationCacheQueryVO queryOpVO = new EduOperationCacheQueryVO();
                queryOpVO.setClassify("2");
                queryOpVO.setAreaCode(studentEnrollVO.getAreaCode());
                queryOpVO.setYear(thisYear);
                EduOperationCacheVO eduOperationCacheVO = eduSystemConfigIntegration.getEduOperation(queryOpVO);
                if (eduOperationCacheVO == null) {
                    throw new AppException("本年度义务教育阶段招生参数未配置，请联系系统管理员");
                }
                Map<String, EduOperationCacheDetailVO> operation = eduOperationCacheVO.getOperation();
                EduOperationCacheDetailVO shOperation = null;
                if (SchoolNatureEnum.mzg.getType().equalsIgnoreCase(studentEnrollVO.getSchoolNature())) {
                    shOperation = operation.get("YW016");//录用业务时间
                } else if (SchoolNatureEnum.mb.getType().equalsIgnoreCase(studentEnrollVO.getSchoolNature())) {
                    //民办第一志愿
                    shOperation = operation.get("YW009");
                }
                if (shOperation != null) {
                    if (shOperation.isFlag() || "2".equalsIgnoreCase(shOperation.getType())) {
                        desensitizeFlag = true;
                    } else {
                        desensitizeFlag = false;
                    }
                } else {
                    desensitizeFlag = false;
                }

            } else {
                desensitizeFlag = true;
            }

        }
        if (desensitizeFlag) {
            if (!EnrollStatusFormalEnum.lq.getType().equalsIgnoreCase(studentEnrollVO.getEnrollStatus())) {
                //录取不脱敏 其他都脱敏
                EduDesensitizeUtil.desensitizeStudentEnroll(studentEnrollVO);
            }
        }
        return studentEnrollVO;
    }
    private void setVerificationMaterial(EduStudentEnrollVerificationVO enrollVerification, EduStudentEnrollVO vo) {
        if (StringUtils.isBlank(enrollVerification.getVerificationType())){
            return;
        }

        //房户一致list
        List<String> fhyzList = new ArrayList<>();
        fhyzList.add(VerificationTypeEnum.yzb.getType());
        fhyzList.add(VerificationTypeEnum.fwq.getType());
        fhyzList.add(VerificationTypeEnum.fhyz.getType());
        fhyzList.add(VerificationTypeEnum.fwqyzb.getType());
        //房产地址学区核验
        List<String> fcdzxqList = new ArrayList<>();
        fcdzxqList.add(VerificationTypeEnum.fwqfc.getType());
        fcdzxqList.add(VerificationTypeEnum.fcdz.getType());
        //户籍地址学区核验
        List<String> hjdzxqList = new ArrayList<>();
        hjdzxqList.add(VerificationTypeEnum.fwqhj.getType());
        hjdzxqList.add(VerificationTypeEnum.hjdz.getType());

        //接收材料信息
        List<EduMateria> materiaList = new ArrayList<>();
        //房户一致
        if (fhyzList.contains(enrollVerification.getVerificationType())){
            //户籍地址
            if (StringUtils.isNotBlank(vo.getHouseholdAddress())){
                EduMateria materia = new EduMateria();
                materia.setMaterialName("学生户籍地址");
                materia.setMaterialTextValue(Convert.toDBC(vo.getHouseholdAddress()));
                materia.setMaterialType("text");
                materiaList.add(materia);
            }
            //房产地址
            if (StringUtils.isNotBlank(vo.getHouseAdreess())){
                EduMateria materia = new EduMateria();
                materia.setMaterialName("报名房产地址");
                materia.setMaterialTextValue(Convert.toDBC(vo.getHouseAdreess()));
                materia.setMaterialType("text");
                materiaList.add(materia);
            }
            //房产佐证材料
            if (StringUtils.isNotBlank(vo.getParam16())){
                EduMateria materia = new EduMateria();
                materia.setMaterialName("房产佐证材料");
                List<String> imageList  = Arrays.asList( vo.getParam16().split(","));
                materia.setMaterialImgValue(imageList);
                materia.setMaterialType("img");
                materiaList.add(materia);

            }
            //户籍佐证材料
            if (StringUtils.isNotBlank(vo.getParam17())){
                EduMateria materia = new EduMateria();
                materia.setMaterialName("户口本");
                List<String> hkbImagList = Arrays.asList(vo.getParam17().split(","));
                materia.setMaterialImgValue(hkbImagList);
                materia.setMaterialType("img");
                materiaList.add(materia);
            }

        } else if (fcdzxqList.contains(enrollVerification.getVerificationType())) {
            //校验房产地址是否为学区
            if (StringUtils.isNotBlank(vo.getHouseholdAddress())){
                EduMateria materia = new EduMateria();
                materia.setMaterialName("报名房产地址");
                materia.setMaterialTextValue(Convert.toDBC(vo.getHouseAdreess()));
                materia.setMaterialType("text");
                materiaList.add(materia);
            }
        }else if (hjdzxqList.contains(enrollVerification.getVerificationType())){
            //校验户籍地址是否为学区
            if (StringUtils.isNotBlank(vo.getHouseholdAddress())){
                EduMateria materia = new EduMateria();
                materia.setMaterialName("学生户籍地址");
                materia.setMaterialTextValue(Convert.toDBC(vo.getHouseholdAddress()));
                materia.setMaterialType("text");
                materiaList.add(materia);
            }
        }else if (VerificationTypeEnum.qzgx.getType().equalsIgnoreCase(enrollVerification.getVerificationType())){
            //校验亲子关系 param12:出生证  param15:结婚证  param17:户口本
            if (StringUtils.isNotBlank(vo.getParam12())){
                EduMateria materia = new EduMateria();
                materia.setMaterialName("出生证或结婚证");
                List<String> cszImagList = Arrays.asList(vo.getParam12().split(","));
                materia.setMaterialImgValue(cszImagList);
                materia.setMaterialType("img");
                materiaList.add(materia);
            }
            if (StringUtils.isNotBlank(vo.getParam15())){
                EduMateria materia = new EduMateria();
                materia.setMaterialName("结婚证");
                List<String> jhzImagList = Arrays.asList(vo.getParam15().split(","));
                materia.setMaterialImgValue(jhzImagList);
                materia.setMaterialType("img");
                materiaList.add(materia);
            }
            if (StringUtils.isNotBlank(vo.getParam17())){
                EduMateria materia = new EduMateria();
                materia.setMaterialName("户口本");
                List<String> hkbImagList = Arrays.asList(vo.getParam17().split(","));
                materia.setMaterialImgValue(hkbImagList);
                materia.setMaterialType("img");
                materiaList.add(materia);
            }
        }else if (VerificationTypeEnum.fc.getType().equalsIgnoreCase(enrollVerification.getVerificationType())){
            //房产
            if (StringUtils.isNotBlank(vo.getParam16())){
                EduMateria materia = new EduMateria();
                materia.setMaterialName("房产佐证材料");
                List<String> imageList  = Arrays.asList( vo.getParam16().split(","));
                materia.setMaterialImgValue(imageList);
                materia.setMaterialType("img");
                materiaList.add(materia);
            }
        }else if (VerificationTypeEnum.hj.getType().equalsIgnoreCase(enrollVerification.getVerificationType())){
            //户籍
            if (StringUtils.isNotBlank(vo.getParam17())){
                EduMateria materia = new EduMateria();
                materia.setMaterialName("户口本");
                List<String> hkbImagList = Arrays.asList(vo.getParam17().split(","));
                materia.setMaterialImgValue(hkbImagList);
                materia.setMaterialType("img");
                materiaList.add(materia);
            }
        } else if (VerificationTypeEnum.sb.getType().equalsIgnoreCase(enrollVerification.getVerificationType())) {
            //社保
            if (StringUtils.isNotBlank(vo.getParam14())) {
                EduMateria materia = new EduMateria();
                materia.setMaterialName("社保");
                materia.setMaterialImgValue(Arrays.asList(vo.getParam14().split(",")));
                materia.setMaterialType("img");
                materiaList.add(materia);
            }
        } else if (VerificationTypeEnum.jzz.getType().equalsIgnoreCase(enrollVerification.getVerificationType())) {
            //居住证
            if (StringUtils.isNotBlank(vo.getParam13())){
                EduMateria materia = new EduMateria();
                materia.setMaterialName("居住证");
                materia.setMaterialImgValue(Arrays.asList(vo.getParam13().split(",")));
                materia.setMaterialType("img");
                materiaList.add(materia);
            }
        }
        enrollVerification.setVerificationMateriaList(materiaList);
    }

    @Override
    @OpApi(funcCode = "enrollImitate0020", title = "义务教育模拟报名人数信息查询", funcType = FuncTypeEnum.query, checkPrivilege = BoolEnum.FALSE)
    public StudentEnrollCntVO queryBmCnt(EduStudentEnrollQueryVO vo) {
        // 开启分页
        if (vo.getPageNum() == null || vo.getPageSize() == null) {
            //如果不传入分页参数，默认最大取1000条
            vo.setPageNum(1);
            vo.setPageSize(20);
        }
        if (vo.getYear() == null) {
            throw new AppException("请输入查询年份");
        }
        EnrollCheckShLqVO checkShLqVO = new EnrollCheckShLqVO();
        checkShLqVO.setYear(vo.getYear());
        checkShLqVO.setOpType(vo.getOpType());
        checkShLqVO.setSchoolId(vo.getSchoolId());
        Boolean flag = checkShLq(checkShLqVO);
        StudentEnrollCntVO retVO = new StudentEnrollCntVO();
        Integer zrs = 0;
        Integer dsh = 0;
        Integer dhy = 0;
        Integer dfh = 0;
        Integer dlq = 0;
        Integer ylq = 0;
        if (!flag) {
            retVO.setZrs(zrs);
            retVO.setDsh(dsh);
            retVO.setDlq(dlq);
            retVO.setYlq(ylq);
            retVO.setJhs(0);
            retVO.setLqFlag(false);
            return retVO;
        }

        QueryWrapper<EduStudentEnrollImitate> queryWrapper = new QueryWrapper<>();
        List<String> enrollStatusList = new ArrayList<>();
        enrollStatusList.add(EnrollStatusFormalEnum.hy.getType());
        enrollStatusList.add(EnrollStatusFormalEnum.fs.getType());
        enrollStatusList.add(EnrollStatusFormalEnum.dsh.getType());
        enrollStatusList.add(EnrollStatusFormalEnum.dlq.getType());
        enrollStatusList.add(EnrollStatusFormalEnum.lq.getType());
        enrollStatusList.add(EnrollStatusFormalEnum.ywblq.getType());
        enrollStatusList.add(EnrollStatusFormalEnum.hybtg.getType());
        queryWrapper.lambda().select(EduStudentEnrollImitate::getEnrollStatus)
                .eq(StringUtils.isNotBlank(vo.getSchoolId()), EduStudentEnrollImitate::getSchoolId, vo.getSchoolId())
                .eq(EduStudentEnrollImitate::getYear, vo.getYear())
                .in(EduStudentEnrollImitate::getEnrollStatus, enrollStatusList)
                .eq(StringUtils.isNotBlank(vo.getConfigTypeName()), EduStudentEnrollImitate::getConfigTypeName, vo.getConfigTypeName())
                .eq(StringUtils.isNotBlank(vo.getConfigName()), EduStudentEnrollImitate::getConfigTypeName, vo.getConfigName())
                .eq(StringUtils.isNotBlank(vo.getFollowingFlag()), EduStudentEnrollImitate::getFollowingFlag, vo.getFollowingFlag());
        List<EduStudentEnrollImitate> list = eduStudentEnrollService.list(queryWrapper);
        if (!CollectionUtils.isEmpty(list)) {
            for (EduStudentEnrollImitate enroll : list) {
                if (EnrollStatusFormalEnum.lq.getType().equals(enroll.getEnrollStatus())) {
                    ylq = ylq + 1;
                }
            }
        }
        queryWrapper.lambda().eq(StringUtils.isNotBlank(vo.getAspirationType()), EduStudentEnrollImitate::getAspirationType, vo.getAspirationType());
        list = eduStudentEnrollService.list(queryWrapper);
        if (!CollectionUtils.isEmpty(list)) {
            zrs = list.size();
            for (EduStudentEnrollImitate enroll : list) {

                if (EnrollStatusFormalEnum.dsh.getType().equals(enroll.getEnrollStatus())) {
                    dsh = dsh + 1;
                }
                if (EnrollStatusFormalEnum.dlq.getType().equals(enroll.getEnrollStatus())) {
                    dlq = dlq + 1;
                }
            }

        }

        retVO.setZrs(zrs);
        retVO.setDsh(dsh);
        retVO.setDlq(dlq);
        retVO.setYlq(ylq);
        QueryWrapper<EduSchoolConfig> configQueryWrapper = new QueryWrapper<>();
        configQueryWrapper.lambda().select(EduSchoolConfig::getEnrolment, EduSchoolConfig::getSerialNumEnd)
                .eq(StringUtils.isNotBlank(vo.getSchoolId()), EduSchoolConfig::getSchoolId, vo.getSchoolId())
                .eq(EduSchoolConfig::getAuthStatus, AuthStatusEnum.YES.getType())
                .eq(EduSchoolConfig::getStatus, BoolEnum.TRUE.getType())
                .eq(EduSchoolConfig::getYear, vo.getYear())
                .eq(StringUtils.isNotBlank(vo.getConfigTypeName()), EduSchoolConfig::getConfigTypeName, vo.getConfigTypeName());
        List<EduSchoolConfig> configList = eduSchoolConfigService.list(configQueryWrapper);
        int jhs = 0;
        if (!CollectionUtils.isEmpty(configList)) {
            for (EduSchoolConfig config : configList) {
                Integer count = config.getEnrolment() == null ? 0 : config.getEnrolment();
                jhs = jhs + count;
            }
        }
        int serialNumEnd = 0;
        if (StringUtils.isNotBlank(vo.getConfigTypeName())) {
            if (!CollectionUtils.isEmpty(configList)) {
                serialNumEnd = configList.get(0).getSerialNumEnd() == null ? 0 : configList.get(0).getSerialNumEnd();
            }
        }
        retVO.setSerialNumEnd(serialNumEnd);
        retVO.setJhs(jhs);
        if (jhs - ylq > 0) {
            retVO.setLqFlag(true);
        } else {
            retVO.setLqFlag(false);
        }
        return retVO;
    }

    @Override
    @OpApi(funcCode = "enrollImitate0037", title = "义务教育教育局报名复审", funcType = FuncTypeEnum.update)
    @SaveOplog(
            operationType = "enrollImitate0037",
            operationName = "义务教育教育局报名复审",
            dataType = "studentEnrollId",
            auType = AuTypeEnum.OTHER)
    @Transactional
    public void ywReview(StudentEnrollSaveVO vo) {
        this.review(vo);
    }

    @Override
    public void checkSh(EnrollCheckShLqVO vo) {
        if (vo.getYear() == null) {
            throw new AppException("年度不能为空");
        }
        if (StringUtils.isBlank(vo.getOpType())) {
            throw new AppException("操作类型不能为空");
        }
        int year = eduHelper.thisYear();
        if (vo.getYear() < year) {
            throw new AppException("招生审核工作已结束，不能审核");
        } else if (vo.getYear() > year) {
            throw new AppException("招生审核工作尚未开始，不能审核");
        }
        // EduEnrollPlan eduEnrollPlan = enrollPlanIntegration.getByYear(year);
        if (StringUtils.isBlank(vo.getAreaCode())) {
            vo.setAreaCode(SessionUtil.getSessionInfo().getAreaCode());
        }
        EduOperationCacheQueryVO cacheQueryVO = Convert.convert(EduOperationCacheQueryVO.class, vo);
        cacheQueryVO.setClassify("2");
        EduOperationCacheVO eduOperationCacheVO = eduSystemConfigIntegration.getEduOperation(cacheQueryVO);
        if (eduOperationCacheVO.getOperation() == null) {
            throw new AppException(year + "年度招生计划参数不存在");
        }
        Long current = DateUtil.currentSeconds();
        if ("0".equals(vo.getOpType())) {
            if (eduOperationCacheVO.getOperation().get("YW064") == null) {
                throw new AppException("模拟报名审核工作尚未开始，不能审核");
            } else {
                if (!eduOperationCacheVO.getOperation().get("YW064").isFlag()) {
                    throw new AppException(eduOperationCacheVO.getOperation().get("YW064").getMessagePrompts() + eduOperationCacheVO.getOperation().get("YW064").getMessageTip());
                }
            }
        }
    }

    //复审
    private void review(StudentEnrollSaveVO vo) {
        if (StringUtils.isBlank(vo.getStudentEnrollId())) {
            throw new AppException("报名id不能为空");
        }
        if (StringUtils.isBlank(vo.getAuthStatus())) {
            throw new AppException("审核状态不能为空");
        }
        if (StringUtils.isBlank(vo.getAreaCode())) {
            vo.setAreaCode(SessionUtil.getSessionInfo().getAreaCode());
        }
        EduStudentEnrollImitate old = eduStudentEnrollService.getById(vo.getStudentEnrollId());
        if (old == null) {
            throw new AppException("报名数据不存在，可能已被回退，请重新查询");
        }
        if (old.getEnrollStatus().equals(EnrollStatusFormalEnum.hy.getType())) {
            throw new AppException("未核验通过，不能进行复审");
        }
        if (old.getEnrollStatus().equals(EnrollStatusFormalEnum.dsh.getType())) {
            throw new AppException("未初审通过，不能进行复审");
        }
        if (old.getEnrollStatus().equals(EnrollStatusFormalEnum.fs.getType())) {
            throw new AppException("学校复审通过，不能进行复审");
        }
        int year;
        year = eduHelper.thisYear();

        if (old.getYear() < year) {
            throw new AppException("历年报名数据不允许审核");
        }
        //业务期判断
        EnrollCheckShLqVO checkShLqVO = new EnrollCheckShLqVO();
        checkShLqVO.setSchoolId(old.getSchoolId());
        checkShLqVO.setYear(old.getYear());
        checkShLqVO.setAreaCode(old.getAreaCode());
        if ("0".equals(old.getSchoolNature()) || "2".equals(old.getSchoolNature())) {
            checkShLqVO.setOpType(old.getSchoolNature());
        }
        if ("1".equals(old.getSchoolNature())) {
            if ("1".equals(old.getAspirationType())) {
                //民办1
                checkShLqVO.setOpType("1");
            }
            if ("2".equals(old.getAspirationType())) {
                //民办2
                checkShLqVO.setOpType("3");
            }
            if ("3".equals(old.getAspirationType())) {
                //民办3
                checkShLqVO.setOpType("4");
            }

        }
        checkSh(checkShLqVO);

        if (!AuthStatusEnum.NODO.getType().equals(old.getAuthStatus())) {
            throw new AppException(old.getFullName() + "的报名数据已审核，请重新查询");
        }


        QueryWrapper<EduEnrollmenBrochure> queryBrochureWrapper = new QueryWrapper<>();
        queryBrochureWrapper.lambda().eq(EduEnrollmenBrochure::getYear, old.getYear())
                .eq(EduEnrollmenBrochure::getSchoolId, old.getSchoolId());
        EduEnrollmenBrochure eduEnrollmenBrochure = eduEnrollmenBrochureService.getOne(queryBrochureWrapper, false);
        if (eduEnrollmenBrochure == null) {
            throw new AppException("未找到招生方案信息");
        }

        if (BoolEnum.TRUE.getType().equals(eduEnrollmenBrochure.getEndRegistration())) {
            throw new AppException("招生已停止，不能审核");
        }

        List<String> enrollStatusList = new ArrayList<>();
        enrollStatusList.add(EnrollStatusFormalEnum.dlq.getType());
        enrollStatusList.add(EnrollStatusFormalEnum.lq.getType());
        enrollStatusList.add(EnrollStatusFormalEnum.fs.getType());
        QueryWrapper<EduStudentEnrollImitate> enrollQueryWrapper = new QueryWrapper<>();
        enrollQueryWrapper.lambda().select(EduStudentEnrollImitate::getStudentEnrollId)
                .eq(EduStudentEnrollImitate::getIdcard, old.getIdcard())
                .in(EduStudentEnrollImitate::getEnrollStatus, enrollStatusList)
                .ne(EduStudentEnrollImitate::getSchoolId, old.getSchoolId());
        if (eduStudentEnrollService.count(enrollQueryWrapper) > 0) {
            throw new AppException(old.getFullName() + "，其他学校资料审核通过或者已录取");
        }
        old.setAuthStatus(vo.getAuthStatus());
        old.setAuthTime(new Date());
        old.setAuthRemarks(vo.getAuthRemarks());
        old.setAuthUserId(SessionUtil.getSessionInfo().getUserId());
        if (AuthStatusEnum.NO.getType().equals(vo.getAuthStatus())) {
            //复审不通过退回到学校待审核
            old.setEnrollStatus(EnrollStatusFormalEnum.dsh.getType());
            //审核状态设置为待审核
            old.setAuthStatus(AuthStatusEnum.NODO.getType());
            old.setAuthRemarks(vo.getAuthRemarks());
            old.setAuthUserId(SessionUtil.getSessionInfo().getUserId());
            old.setAuthTime(new Date());
            //删除审核数据
            eduStudentEnrollReviewService.remove(new QueryWrapper<EduStudentEnrollReview>().lambda().eq(EduStudentEnrollReview::getStudentEnrollId, old.getStudentEnrollId()));
        } else {
            old.setEnrollStatus(EnrollStatusFormalEnum.fs.getType());
        }
        //todo 保存审核记录表
        EduStudentEnrollReviewVO eduStudentEnrollReview = new EduStudentEnrollReviewVO();
        SessionInfo sessionInfo = SessionUtil.getSessionInfo();
        eduStudentEnrollReview.setStudentEnrollId(old.getStudentEnrollId());
        eduStudentEnrollReview.setAuditType(EnrollReviewStatusFormalEnum.fs.getType());
        eduStudentEnrollReview.setAuthUserId(sessionInfo.getUserId());
        eduStudentEnrollReview.setAuthUserName(sessionInfo.getUserName());
        eduStudentEnrollReview.setOrgId(sessionInfo.getOrgId());
        eduStudentEnrollReview.setOrgName(sessionInfo.getOrgName());
        eduStudentEnrollReview.setAuthStatus(vo.getAuthStatus());
        eduStudentEnrollReview.setAuthTime(new Date());
        eduStudentEnrollReview.setAuthRemarks(vo.getAuthRemarks());
        eduStudentEnrollReviewService.save(Convert.convert(EduStudentEnrollReview.class, eduStudentEnrollReview));
        eduStudentEnrollService.updateById(old);
        eduEnrollClearCacheHelper.clearCacheMyEnroll(old.getIdcard());
        eduEnrollClearCacheHelper.clearCacheMyEnroll(old.getFatherIdcard());
        eduEnrollClearCacheHelper.clearCacheMyEnroll(old.getMotherIdcard());
    }
    @Override
    @OpApi(funcCode = "enrollImitate0021", title = "义务教育公办模拟报名信息导出", funcType = FuncTypeEnum.other, checkPrivilege = BoolEnum.FALSE)
    public void exportYwGbApplyInfo(EduStudentEnrollQueryVO vo, HttpServletResponse response) {
        vo.setSchoolId(SessionUtil.getOrgId());
        vo.setOpType("0");
        if (vo.getYear() == null) {
            throw new AppException("招生年度不能为空");
        }
        this.exportYwApplyInfo(vo, response);
    }
    public void exportYwApplyInfo(EduStudentEnrollQueryVO vo, HttpServletResponse response) {
        ExcelVO excelVO = new ExcelVO();
        excelVO.setModelCode(vo.getModelCode());
        ExcelModelVO excelModelVO = excelIntegration.getModel(excelVO);

        String destFilePath = this.tempPath + "/" + IdUtil.fastSimpleUUID() + "." + excelModelVO.getExcelType();
        int pageNum = 1;
        setDataexportYwApplyInfo(excelModelVO, null, destFilePath, vo, pageNum);
        String fileName = vo.getFileName();
        if (StringUtils.isBlank(fileName)) {
            fileName =
                    excelModelVO.getModelName()+"模拟报名"
                            + "_"
                            + DateUtil.format(DateUtil.date(), DatePattern.PURE_DATETIME_PATTERN)
                            + "."
                            + (StringUtils.isBlank(excelModelVO.getExcelType())
                            ? "xls"
                            : excelModelVO.getExcelType());
        }
        File file = FileUtil.file(destFilePath);
        BufferedInputStream in = null;
        try {
            in = FileUtil.getInputStream(file);
            ServletUtil.write(response, in, "application/octet-stream;charset=utf-8", fileName);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            FileUtil.del(destFilePath);
        }

    }
    private void setDataexportYwApplyInfo(ExcelModelVO excelModelVO, ExcelWriter excelWriter, String destFilePath, EduStudentEnrollQueryVO vo, int pageNum) {
        vo.setPageNum(pageNum);
        vo.setPageSize(500);
        boolean closeFlag = false;
        try {
            vo.setDesensitizeFlag(false);
            PageInfo<EduStudentEnrollVO> pageInfo = getList(vo);
            String total = String.valueOf(pageInfo.getTotal());
            List<Object> list = new ArrayList<>();
            if (!CollectionUtils.isEmpty(pageInfo.getList())) {
                for (EduStudentEnrollVO eduStudentEnrollVO : pageInfo.getList()) {
                    list.add(eduStudentEnrollVO);
                }
            }
            if (pageNum == 1) {
                if (excelWriter == null) {
                    excelWriter = excelCommonHelper.createExcelWriter(excelModelVO, destFilePath, Integer.parseInt(total));
                }
                excelCommonHelper.writeBean(excelWriter, list);
            } else {
                excelCommonHelper.writeBean(excelWriter, list);
            }
            if (pageInfo.isHasNextPage()) {
                pageNum = pageNum + 1;
                setDataexportYwApplyInfo(excelModelVO, excelWriter, destFilePath, vo, pageNum);
            } else {
                closeFlag = true;
            }
        } catch (AppException appEx) {
            throw appEx;
        } catch (Exception e) {
            throw new AppException("调用自定义写入服务异常:" + e.getMessage());
        } finally {
            if (closeFlag && excelWriter != null) {
                excelWriter.close();
            }
        }
    }

}
